package com.red.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.red.context.BaseContext;
import com.red.entity.Address;
import com.red.mapper.AddressMapper;
import com.red.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 查询当前用户添加的所有地址
     * @return
     */
    public List<Address> selectAll() {

        Long userId = BaseContext.getCurrentId();
        QueryWrapper<Address> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        qw.eq("is_default",1);
        List<Address> addressList1 = addressMapper.selectList(qw);
        QueryWrapper<Address> qw2 = new QueryWrapper<>();
        qw2.eq("user_id",userId);
        qw2.eq("is_default",0);
        List<Address> addressList2 = addressMapper.selectList(qw2);
        if (addressList2 != null && !addressList2.isEmpty()){
            addressList1.addAll(addressList2);
        }

        return addressList1;
    }

    /**
     * 添加地址信息
     * @param address
     */
    public void insert(Address address) {
        address.setUserId(1L);
        //判断添加的是不是默认地址
        if (address.getIsDefault() == 1){
            //是 把原来的默认地址更改
            QueryWrapper<Address> qw = new QueryWrapper<>();
            qw.eq("is_default",1);
            Address address1 = addressMapper.selectOne(qw);
            if (address1!=null){
                //把原来的默认地址更改
                address1.setIsDefault(0);
                addressMapper.updateById(address1);
            }
            //添加地址
            addressMapper.insert(address);
        }else {
            //不是 直接添加
            addressMapper.insert(address);
        }


    }

    /**
     * 更改地址状态
     * @param address
     */
    public void updateIsDefault(Address address) {

        if (address.getIsDefault() == 1){
            //是 把原来的默认地址更改
            QueryWrapper<Address> qw = new QueryWrapper<>();
            qw.eq("is_default",1);
            Address address1 = addressMapper.selectOne(qw);
            if (address1!=null){
                //把原来的默认地址更改
                address1.setIsDefault(0);
                addressMapper.updateById(address1);
            }
        }else {
            addressMapper.updateById(address);
        }
    }

    /**
     * 删除地址信息
     * @param id
     */
    public void deleteById(Long id) {
        addressMapper.deleteById(id);
    }


}
